import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/api';

export const useTokenStore = defineStore('tokens', () => {
  const tokens = ref([]);
  const currentToken = ref(null);
  const loading = ref(false);
  
  /**
   * 获取所有令牌
   */
  async function fetchTokens(params = {}) {
    loading.value = true;
    try {
      const response = await api.get('/tokens', { params });
      tokens.value = response.data.data.tokens;
      return response.data.data;
    } catch (error) {
      throw error;
    } finally {
      loading.value = false;
    }
  }
  
  /**
   * 获取单个令牌
   */
  async function fetchToken(id) {
    try {
      const response = await api.get(`/tokens/${id}`);
      currentToken.value = response.data.data;
      return currentToken.value;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 创建令牌
   */
  async function createToken(tokenData) {
    try {
      const response = await api.post('/tokens', tokenData);
      tokens.value.unshift(response.data.data);
      return response.data.data;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 更新令牌
   */
  async function updateToken(id, tokenData) {
    try {
      const response = await api.put(`/tokens/${id}`, tokenData);
      const index = tokens.value.findIndex(t => t.id === id);
      if (index !== -1) {
        tokens.value[index] = response.data.data;
      }
      return response.data.data;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 删除令牌
   */
  async function deleteToken(id) {
    try {
      await api.delete(`/tokens/${id}`);
      tokens.value = tokens.value.filter(t => t.id !== id);
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 生成TOTP验证码
   */
  async function generateCode(id, password) {
    try {
      const response = await api.post(`/tokens/${id}/generate`, { password });
      return response.data.data;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 切换收藏
   */
  async function toggleFavorite(id) {
    try {
      const response = await api.patch(`/tokens/${id}/favorite`);
      const index = tokens.value.findIndex(t => t.id === id);
      if (index !== -1) {
        tokens.value[index].isFavorite = response.data.data.isFavorite;
      }
      return response.data.data.isFavorite;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 批量删除
   */
  async function batchDelete(tokenIds) {
    try {
      const response = await api.post('/tokens/batch-delete', { tokenIds });
      tokens.value = tokens.value.filter(t => !tokenIds.includes(t.id));
      return response.data.data.count;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 搜索令牌
   */
  async function searchTokens(query, category) {
    loading.value = true;
    try {
      const response = await api.get('/tokens/search', {
        params: { q: query, category },
      });
      tokens.value = response.data.data.tokens;
      return response.data.data;
    } catch (error) {
      throw error;
    } finally {
      loading.value = false;
    }
  }
  
  /**
   * 获取收藏的令牌
   */
  async function fetchFavorites() {
    try {
      const response = await api.get('/tokens/favorites');
      return response.data.data.tokens;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 导入令牌
   */
  async function importToken(uri, password) {
    try {
      const response = await api.post('/tokens/import', { uri, password });
      tokens.value.unshift(response.data.data);
      return response.data.data;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 导出令牌
   */
  async function exportTokens() {
    try {
      const response = await api.get('/tokens/export');
      return response.data.data;
    } catch (error) {
      throw error;
    }
  }
  
  return {
    tokens,
    currentToken,
    loading,
    fetchTokens,
    fetchToken,
    createToken,
    updateToken,
    deleteToken,
    generateCode,
    toggleFavorite,
    batchDelete,
    searchTokens,
    fetchFavorites,
    importToken,
    exportTokens,
  };
});


